#include <QFile>
#include <QFileDialog>
#include <QTextStream>
#include <QMessageBox>
#if defined(QT_PRINTSUPPORT_LIB)
#include <QtPrintSupport/qtprintsupportglobal.h>
#if QT_CONFIG(printer)
#if QT_CONFIG(printdialog)
#include <QPrintDialog>
#endif // QT_CONFIG(printdialog)
#include <QPrinter>
#endif // QT_CONFIG(printer)
#endif // QT_PRINTSUPPORT_LIB
#include <QFont>
#include <QFontDialog>
#include <QColorDialog>
#include <QPainter>

#include "mainwindow.h"
#include "./ui_mainwindow.h"
#include "visitorlist.h"
#include "alarmmessage.h"
#include "imageprint.h"
#include "barcodebox.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setWindowTitle("硬件综合应用");

    // create statusbar
    QStatusBar* statusBar = new QStatusBar(this);
    setStatusBar(statusBar);
    statusLabel = new QLabel("", this);
    statusLabel->setFrameStyle(QFrame::Box | QFrame::Sunken);
    statusBar->addPermanentWidget(statusLabel);

    // set statusbar showtime
    statusBar->showMessage(tr("welcome to use uos 硬件综合应用"), 2000);

    connect(ui->actionNew, &QAction::triggered, this, &MainWindow::newDocument);
    connect(ui->actionOpen, &QAction::triggered, this, &MainWindow::open);
    connect(ui->actionSave, &QAction::triggered, this, &MainWindow::save);
    connect(ui->actionSaveAs, &QAction::triggered, this, &MainWindow::saveAs);
    connect(ui->actionPrint, &QAction::triggered, this, &MainWindow::print);
    connect(ui->actionExit, &QAction::triggered, this, &QWidget::close);
#if QT_CONFIG(clipboard)
    connect(ui->textEdit, &QTextEdit::copyAvailable, ui->actionCopy, &QAction::setEnabled);
    connect(ui->actionCopy, &QAction::triggered, ui->textEdit, &QTextEdit::copy);
    connect(ui->actionCut, &QAction::triggered, ui->textEdit, &QTextEdit::cut);
    connect(ui->actionPaste, &QAction::triggered, ui->textEdit, &QTextEdit::paste);
#endif
    connect(ui->textEdit, &QTextEdit::undoAvailable, ui->actionUndo, &QAction::setEnabled);
    connect(ui->actionUndo, &QAction::triggered, ui->textEdit, &QTextEdit::undo);
    connect(ui->textEdit, &QTextEdit::redoAvailable, ui->actionRedo, &QAction::setEnabled);
    connect(ui->actionRedo, &QAction::triggered, ui->textEdit, &QTextEdit::redo);

    connect(ui->actionFont, &QAction::triggered, this, &MainWindow::selectFont);
    connect(ui->actionColor, &QAction::triggered, this, &MainWindow::setColor);
    connect(ui->actionBold, &QAction::triggered, this, &MainWindow::setFontBold);
    connect(ui->actionUnderline, &QAction::triggered, this, &MainWindow::setFontUnderline);
    connect(ui->actionItalic, &QAction::triggered, this, &MainWindow::setFontItalic);
    connect(ui->actionAbout, &QAction::triggered, this, &MainWindow::about);
    connect(ui->actionRightAlign, &QAction::triggered, this, &MainWindow::setRightAlign);
    connect(ui->actionLeftAlign, &QAction::triggered, this, &MainWindow::setLeftAlign);
    connect(ui->actionCenterAlign, &QAction::triggered, this, &MainWindow::setCenterAlign);

    connect(ui->textEdit, &QTextEdit::textChanged, this, &MainWindow::setStatusBarSize);

// Disable menu actions for unavailable features
#if !defined(QT_PRINTSUPPORT_LIB) || !QT_CONFIG(printer)
    ui->actionPrint->setEnabled(false);
#endif

#if !QT_CONFIG(clipboard)
    ui->actionCut->setEnabled(false);
    ui->actionCopy->setEnabled(false);
    ui->actionPaste->setEnabled(false);
#endif

    ui->lineEditQRMessage->setText("QR code!");
    auto image = m_generator.generateQr(ui->lineEditQRMessage->text());
    QPixmap pixMap = QPixmap::fromImage(image).scaled(331, 221, Qt::KeepAspectRatio, Qt::FastTransformation);

    // Display generated image
    ui->labelQRcodeImg->setPixmap(pixMap);


    barCodeBox = new BarCodeBox();
    ui->lineEditBarcodeNum->setText("Barcode!");
    barCodeBox->setBarCode(ui->lineEditBarcodeNum->text(), BarCode::CODE_128B_TYPE);//设置条码
    barCodeBox->generateBar();//重新绘制
    ui->labelBarcodeImg->setPixmap(barCodeBox->pixmap);

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::newDocument()
{
    currentFile.clear();
    ui->textEdit->setText(QString());
}

void MainWindow::setTextEdit(const QString& text)
{
    currentFile.clear();
    ui->textEdit->setText(text);
}

void MainWindow::open()
{
    QString fileName = QFileDialog::getOpenFileName(this, "Open the file");
    if (fileName.isEmpty())
        return;
    QFile file(fileName);
    currentFile = fileName;
    if (!file.open(QIODevice::ReadOnly | QFile::Text)) {
        QMessageBox::warning(this, "Warning", "Cannot open file: " + file.errorString());
        return;
    }
    setWindowTitle(fileName);
    QTextStream in(&file);
    QString text = in.readAll();
    ui->textEdit->setText(text);
    file.close();
}

void MainWindow::save()
{
    QString fileName;
    // If we don't have a filename from before, get one.
    if (currentFile.isEmpty()) {
        fileName = QFileDialog::getSaveFileName(this, "Save");
        if (fileName.isEmpty())
            return;
        currentFile = fileName;
    } else {
        fileName = currentFile;
    }
    QFile file(fileName);
    if (!file.open(QIODevice::WriteOnly | QFile::Text)) {
        QMessageBox::warning(this, "Warning", "Cannot save file: " + file.errorString());
        return;
    }
    setWindowTitle(fileName);
    QTextStream out(&file);
    QString text = ui->textEdit->toPlainText();
    out << text;
    file.close();
}

void MainWindow::saveAs()
{
    QString fileName = QFileDialog::getSaveFileName(this, "Save as");
    if (fileName.isEmpty())
        return;
    QFile file(fileName);

    if (!file.open(QFile::WriteOnly | QFile::Text)) {
        QMessageBox::warning(this, "Warning", "Cannot save file: " + file.errorString());
        return;
    }
    currentFile = fileName;
    setWindowTitle(fileName);
    QTextStream out(&file);
    QString text = ui->textEdit->toPlainText();
    out << text;
    file.close();
}

void MainWindow::print()
{
#if defined(QT_PRINTSUPPORT_LIB) && QT_CONFIG(printer)
    QPrinter printDev;
#if QT_CONFIG(printdialog)
    QPrintDialog dialog(&printDev, this);
    if (dialog.exec() == QDialog::Rejected)
        return;
#endif // QT_CONFIG(printdialog)
    ui->textEdit->print(&printDev);
#endif // QT_CONFIG(printer)
}

void MainWindow::selectFont()
{
    bool fontSelected;
    QFont font = QFontDialog::getFont(&fontSelected, this);
    if (fontSelected)
        ui->textEdit->setFont(font);
}

void MainWindow::setColor() {
    QColor color = QColorDialog::getColor(Qt::green, this, tr("select color"));
    if(color.isValid()) {
        ui->textEdit->setTextColor(color);
    }
}

void MainWindow::setFontUnderline(bool underline)
{
    ui->textEdit->setFontUnderline(underline);
}

void MainWindow::setFontItalic(bool italic)
{
    ui->textEdit->setFontItalic(italic);
}

void MainWindow::setFontBold(bool bold)
{
    bold ? ui->textEdit->setFontWeight(QFont::Bold) :
        ui->textEdit->setFontWeight(QFont::Normal);
}

void MainWindow::about()
{
    QMessageBox::about(this, tr("关于"),
                       tr("硬件综合应用"));
}

void MainWindow::setStatusBarSize()
{
    QString text = QString("字数%1").arg(ui->textEdit->toPlainText().length() );
    statusLabel->setText(text);
}

void MainWindow::setRightAlign()
{
    ui->textEdit->setAlignment(Qt::AlignRight);
}


void MainWindow::setLeftAlign()
{
    ui->textEdit->setAlignment(Qt::AlignLeft);
}


void MainWindow::setCenterAlign()
{
    ui->textEdit->setAlignment(Qt::AlignCenter);
}


void MainWindow::on_actionVisitorGenerate_triggered()
{
    auto vistorList = new VisitorList(this);
    vistorList->show();
}


void MainWindow::on_actionGeneratePoliceInfo_triggered()
{
    auto alarmInfo = new AlarmMessage(this);
    alarmInfo->show();
}


void MainWindow::on_lineEditQRMessage_textChanged(const QString &arg1)
{
    auto image = m_generator.generateQr(arg1);
    m_QRImg = QPixmap::fromImage(image).scaled(331, 221, Qt::KeepAspectRatio, Qt::FastTransformation);

    ui->labelQRcodeImg->setPixmap(m_QRImg);
}


void MainWindow::on_actionQRcodePrint_triggered()
{
    QPrinter printer(QPrinter::HighResolution);
    printer.setOutputFileName("QRcode.pdf");
    printer.setPageMargins(QMarginsF(0,0,0,0));
    QPainter painter;
    painter.begin(&printer);

    double xscale = printer.pageRect().width();
    double yscale = printer.pageRect().height() ;
    double scale = qMin(xscale, yscale);
    painter.drawPixmap (30, 30, m_QRImg.scaled(scale / 2, scale / 2));
    painter.end();
    QPrintDialog dialog(&printer);
    dialog.exec();
}


void MainWindow::on_actionPoliceInfoPrint_triggered()
{
    print();
}


void MainWindow::on_actionVistorPrint_triggered()
{
    print();
}


void MainWindow::on_lineEditBarcodeNum_textChanged(const QString &arg1)
{
    barCodeBox->setBarCode(arg1, BarCode::CODE_128B_TYPE);//设置条码
    barCodeBox->generateBar();//重新绘制
    ui->labelBarcodeImg->setPixmap(barCodeBox->pixmap);
}


void MainWindow::on_actionBarcodePrinter_triggered()
{
    QPrinter printer(QPrinter::HighResolution);
    printer.setOutputFileName("Barcode.pdf");
    printer.setPageMargins(QMarginsF(0,0,0,0));
    QPainter painter;
    painter.begin(&printer);

    double xscale = printer.pageRect().width();
    double yscale = printer.pageRect().height() ;
    double scale = qMin(xscale, yscale);
    painter.drawPixmap (0, 0, barCodeBox->pixmap.scaled(scale, scale/4));
    painter.end();
    QPrintDialog dialog(&printer);
    dialog.exec();
}


void MainWindow::on_actionImportImg_triggered()
{
    auto imgPrint = new ImagePrint(this);
    imgPrint->show();
}

